package model;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import helperclasses.DbUtil;
import helperclasses.Furnizori;

public class ModifyFurnizori {

	public ModifyFurnizori() {

	}

	private Connection getConnection() throws SQLException {

		DataSource ds = DbUtil.getInstance().getDataSource();
		Connection conn = ds.getConnection();
		return conn;
	}

	public boolean SaveFurnizori(Furnizori furn) throws SQLException {
		Connection conn = getConnection();
		Statement st = conn.createStatement();
		String sql;
		boolean succes = true;

		sql = "INSERT INTO furnizori (furnizor_id, nume, adresa, telefon) VALUES( null, '" + furn.getFurnizorName() + "', '"
				+ furn.getFurnizorAddress() + "', '" + furn.getFurnizorTelephone() + "')";
		try {
			conn.setAutoCommit(false);
			st.executeUpdate(sql);
			conn.commit();

		} catch (SQLException e) {
			e.printStackTrace();
			try {
				// An error occured so we rollback the changes.
				conn.rollback();
				succes = false;
			} catch (SQLException ex1) {
				ex1.printStackTrace();
			}
		} finally {
			st.close();
			conn.close();
		}
		return succes;
	}

	public boolean EditFurnizori(Furnizori furn) throws SQLException {
		Connection conn = getConnection();
		Statement st = conn.createStatement();
		String sql;
		boolean succes = true;

		sql = "UPDATE furnizori SET nume='" + furn.getFurnizorName() + "', adresa='" + furn.getFurnizorAddress() + "', telefon='"
				+ furn.getFurnizorTelephone() + "' WHERE furnizor_id=" + furn.getFurnizorId();
		try {
			conn.setAutoCommit(false);
			st.executeUpdate(sql);
			conn.commit();

		} catch (SQLException e) {
			e.printStackTrace();
			try {
				// An error occured so we rollback the changes.
				conn.rollback();
				succes = false;
			} catch (SQLException ex1) {
				ex1.printStackTrace();
			}
		} finally {
			st.close();
			conn.close();
		}
		return succes;
	}

}
